<?php
/**
* @file $Id: StudentFieldBreakdown.php 295 2006-11-15 04:39:23Z focus-sis $
* @package Focus/SIS
* @copyright Copyright (C) 2006 Andrew Schmadeke. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.txt
* Focus/SIS is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.txt for copyright notices and details.
*/

include('../../Warehouse.php');
include($staticpath.'/assets/SWF/charts.php');
include $staticpath.'/ProgramFunctions/_makeLetterGrade.fnc.php';

if(!$_REQUEST['assignment_id'])
	$_REQUEST['assignment_id'] = 'totals';

$course_id = DBGet(DBQuery("SELECT c.GRAD_SUBJECT_ID,cp.COURSE_ID,cp.TITLE,c.TITLE AS COURSE_TITLE,c.SHORT_NAME AS COURSE_NUM,cw.CREDITS,cw.GPA_MULTIPLIER,cp.DOES_GRADES,cp.GRADE_SCALE_ID,cp.DOES_GPA as AFFECTS_GPA FROM COURSE_PERIODS cp,COURSES c,COURSE_WEIGHTS cw WHERE cw.COURSE_ID=cp.COURSE_ID AND cw.COURSE_WEIGHT=cp.COURSE_WEIGHT AND c.COURSE_ID=cp.COURSE_ID AND cp.COURSE_PERIOD_ID='".UserCoursePeriod()."'"));
$grade_scale_id = $course_id[1]['GRADE_SCALE_ID'];
$course_id = $course_id[1]['COURSE_ID'];

$grades_RET = DBGet(DBQuery("SELECT ID,TITLE FROM REPORT_CARD_GRADES WHERE SCALE_ID='".$grade_scale_id."' AND SYEAR='".UserSyear()."' AND SCHOOL_ID='".UserSchool()."' ORDER BY SORT_ORDER"));
foreach($grades_RET as $grade)
	$grades[] = $grade['TITLE'];

$grades[] = _('N/A');

$config_RET = DBGet(DBQuery("SELECT TITLE,VALUE FROM PROGRAM_USER_CONFIG WHERE USERNAME='".User('USERNAME')."' AND PROGRAM='Gradebook'"),array(),array('TITLE'));
if(count($config_RET))
{
	foreach($config_RET as $title=>$value)
		$programconfig[$title] = $value[1]['VALUE'];
}

$sql = "SELECT ASSIGNMENT_TYPE_ID,TITLE FROM GRADEBOOK_ASSIGNMENT_TYPES WHERE STAFF_ID='".User('STAFF_ID')."' AND COURSE_ID='".$course_id."' ORDER BY TITLE";
$types_RET = DBGet(DBQuery($sql));

$assignments_RET = DBGet(DBQuery("SELECT ASSIGNMENT_ID,TITLE,POINTS FROM GRADEBOOK_ASSIGNMENTS WHERE STAFF_ID='".User('STAFF_ID')."' AND ((COURSE_ID='$course_id' AND STAFF_ID='".User('STAFF_ID')."') OR COURSE_PERIOD_ID='".UserCoursePeriod()."') AND MARKING_PERIOD_ID='".UserMP()."' ORDER BY ".Preferences('ASSIGNMENT_SORTING','Gradebook')." DESC"));
$assignment_select = '<SELECT name=assignment_id onchange="document.location.href=\'Modules.php?modname='.$_REQUEST['modname'].'&assignment_id=\'+this.options[selectedIndex].value"><OPTION value="totals"'.($_REQUEST['assignment_id']=='totals'?' SELECTED':'').'>'._('Totals').'</OPTION>';
foreach($types_RET as $type)
{
	$assignment_select .= '<OPTION value=totals'.$type['ASSIGNMENT_TYPE_ID'].(($_REQUEST['assignment_id']==('totals'.$type['ASSIGNMENT_TYPE_ID']))?' SELECTED':'').'>'.$type['TITLE'].'</OPTION>';
	if($_REQUEST['assignment_id']==('totals'.$type['ASSIGNMENT_TYPE_ID']))
		$title = $type['TITLE'];
}

if(count($assignments_RET))
{
	foreach($assignments_RET as $assignment)
	{
		$assignment_select .= '<OPTION value='.$assignment['ASSIGNMENT_ID'].(($_REQUEST['assignment_id']==$assignment['ASSIGNMENT_ID'])?' SELECTED':'').'>'.$assignment['TITLE'].'</OPTION>';
		if($_REQUEST['assignment_id']==$assignment['ASSIGNMENT_ID'])
			$title = $assignment['TITLE'];
	}
}
$assignment_select .= '</SELECT>';

if($_REQUEST['assignment_id']=='totals')
{
	$title = _('Grade');
	$extra['SELECT_ONLY'] .= "ssm.STUDENT_ID,'' AS LETTER_GRADE";
	$extra['functions'] = array('LETTER_GRADE'=>'_makeGrade');

	$current_RET = DBGet(DBQuery("SELECT g.STUDENT_ID,sum(".db_case(array('g.POINTS',"'-1'","'0'",'g.POINTS')).") AS POINTS,sum(".db_case(array('g.POINTS',"'-1'","'0'",'a.POINTS')).") AS TOTAL_POINTS FROM GRADEBOOK_GRADES g,GRADEBOOK_ASSIGNMENTS a WHERE a.ASSIGNMENT_ID=g.ASSIGNMENT_ID AND a.MARKING_PERIOD_ID='".UserMP()."' AND g.COURSE_PERIOD_ID='".UserCoursePeriod()."' AND (a.COURSE_PERIOD_ID='".UserCoursePeriod()."' OR a.COURSE_ID='$course_id') GROUP BY g.STUDENT_ID"),array(),array('STUDENT_ID'));

	if($programconfig['WEIGHT']=='Y')
		$percent_RET = DBGet(DBQuery("SELECT gt.ASSIGNMENT_TYPE_ID,gg.STUDENT_ID,".db_case(array("sum(".db_case(array('gg.POINTS',"'-1'","'0'",'ga.POINTS')).")","'0'","'0'","(sum(".db_case(array('gg.POINTS',"'-1'","'0'",'gg.POINTS')).") * gt.FINAL_GRADE_PERCENT / sum(".db_case(array('gg.POINTS',"'-1'","'0'",'ga.POINTS'))."))"))." AS PARTIAL_PERCENT FROM GRADEBOOK_GRADES gg, GRADEBOOK_ASSIGNMENTS ga, GRADEBOOK_ASSIGNMENT_TYPES gt WHERE gt.ASSIGNMENT_TYPE_ID=ga.ASSIGNMENT_TYPE_ID AND ga.ASSIGNMENT_ID=gg.ASSIGNMENT_ID AND ga.MARKING_PERIOD_ID IN (".GetAllMP('QTR',UserMP()).") AND gg.COURSE_PERIOD_ID='".UserCoursePeriod()."' AND gt.COURSE_ID='$course_id' GROUP BY gg.STUDENT_ID,gt.ASSIGNMENT_TYPE_ID,gt.FINAL_GRADE_PERCENT"),array(),array('STUDENT_ID','ASSIGNMENT_TYPE_ID'));

	foreach($assignments_RET as $assignment)
		$total_points[$assignment['ASSIGNMENT_ID']] = $assignment['POINTS'];
}
elseif(!is_numeric($_REQUEST['assignment_id']))
{
	$type_id = substr($_REQUEST['assignment_id'],6);
	$extra['SELECT_ONLY'] .= "ssm.STUDENT_ID,'' AS LETTER_GRADE";
	$extra['functions'] = array('LETTER_GRADE'=>'_makeGrade');

	$current_RET = DBGet(DBQuery("SELECT g.STUDENT_ID,sum(".db_case(array('g.POINTS',"'-1'","'0'",'g.POINTS')).") AS POINTS,sum(".db_case(array('g.POINTS',"'-1'","'0'",'a.POINTS')).") AS TOTAL_POINTS FROM GRADEBOOK_GRADES g,GRADEBOOK_ASSIGNMENTS a WHERE a.ASSIGNMENT_ID=g.ASSIGNMENT_ID AND a.MARKING_PERIOD_ID='".UserMP()."' AND g.COURSE_PERIOD_ID='".UserCoursePeriod()."' AND (a.COURSE_PERIOD_ID='".UserCoursePeriod()."' OR a.COURSE_ID='$course_id') AND a.ASSIGNMENT_TYPE_ID='$type_id' GROUP BY g.STUDENT_ID"),array(),array('STUDENT_ID'));

	if($programconfig['WEIGHT']=='Y')
		$percent_RET = DBGet(DBQuery("SELECT gt.ASSIGNMENT_TYPE_ID,gg.STUDENT_ID,".db_case(array("sum(".db_case(array('gg.POINTS',"'-1'","'0'",'ga.POINTS')).")","'0'","'0'","(sum(".db_case(array('gg.POINTS',"'-1'","'0'",'gg.POINTS')).") / sum(".db_case(array('gg.POINTS',"'-1'","'0'",'ga.POINTS'))."))"))." AS PARTIAL_PERCENT FROM GRADEBOOK_GRADES gg, GRADEBOOK_ASSIGNMENTS ga, GRADEBOOK_ASSIGNMENT_TYPES gt WHERE gt.ASSIGNMENT_TYPE_ID=ga.ASSIGNMENT_TYPE_ID AND ga.ASSIGNMENT_TYPE_ID='$type_id' AND ga.ASSIGNMENT_ID=gg.ASSIGNMENT_ID AND ga.MARKING_PERIOD_ID IN (".GetAllMP('QTR',UserMP()).") AND gg.COURSE_PERIOD_ID='".UserCoursePeriod()."' AND gt.COURSE_ID='$course_id' GROUP BY gg.STUDENT_ID,gt.ASSIGNMENT_TYPE_ID,gt.FINAL_GRADE_PERCENT"),array(),array('STUDENT_ID','ASSIGNMENT_TYPE_ID'));

	foreach($assignments_RET as $assignment)
		$total_points[$assignment['ASSIGNMENT_ID']] = $assignment['POINTS'];	
}
elseif($_REQUEST['assignment_id'])
{
	$extra['SELECT_ONLY'] .= "ssm.STUDENT_ID,'' AS LETTER_GRADE";
	$extra['functions'] = array('LETTER_GRADE'=>'_makeGrade');
	$total_points = DBGet(DBQuery("SELECT POINTS FROM GRADEBOOK_ASSIGNMENTS WHERE ASSIGNMENT_ID='$_REQUEST[assignment_id]'"));
	$total_points = $total_points[1]['POINTS'];
	$current_RET = DBGet(DBQuery("SELECT STUDENT_ID,POINTS,COMMENT,ASSIGNMENT_ID FROM GRADEBOOK_GRADES WHERE ASSIGNMENT_ID='$_REQUEST[assignment_id]' AND COURSE_PERIOD_ID='".UserCoursePeriod()."'"),array(),array('STUDENT_ID','ASSIGNMENT_ID'));
}

if(!$_REQUEST['chart_type'])
	$_REQUEST['chart_type'] = 'column';

//		$_REQUEST['modfunc'] = 'SendChartData';

if($_REQUEST['modfunc']=='SendChartData' || $_REQUEST['chart_type']=='list')
{
	$chart['chart_type'] = $_REQUEST['chart_type'];
	$chart['series_switch'] = true;
	if($category_RET[1]['TYPE']=='numeric')
		$width = 400;
	else
		$width = 30*count($grades) < 500 ? 500 : (30*count($grades));
	if($_REQUEST['chart_type']=='column')
	{
		$chart['legend_rect'] = array('x'=>-1000,'y'=>-1000);
		$chart['chart_value'] = array('position'=>'outside','size'=>15);
		$chart['axis_category'] = array('orientation'=>'diagonal_up','size'=>13);
		$chart['axis_value']['size'] = 13;
		$height = 355;
		$chart['chart_rect'] = array('x'=>50,'y'=>45,'width'=>$width,'height'=>$height);
	}
	elseif($_REQUEST['chart_type']=='3d pie')
	{
		$chart['legend_label']['size'] = 13;
		$height = $width-100;
		$width = 400;
		$chart['chart_rect'] = array('x'=>150,'y'=>45,'width'=>$width,'height'=>$height);
		$chart['legend_bg'] = array ('bg_color'=>Preferences('COLOR'),'border_color'=>'000000','border_alpha'=>0,'border_thickness'=>0);
	}
	$chart['draw_text']  = array(array('x'=>0,'y'=>5,'width'=>$width+100,'height'=>200,'h_align'=>'center','v_align'=>'top','rotation'=>0,'text'=>wordwrap($title.' '._('Breakdown'),30,"\r"),'font'=>'Arial','color'=>'000000','alpha'=>25,'size'=>35));
	$chart['chart_bg'] = array('positive_color'=>Preferences('COLOR'),'negative_color'=>'000000');
	$chart['series_color'] = array("00ff88","ffaa00","44aaff","aa00ff","4e627c","844648","ddaa41","88dd11","4e62dd","ff8811","4d4d4d","4e627c","c89341","4c6b41","5a4b6e","3b5743","303d3d","4c5e6f","564546","784e3a","677b75");
	
	if($category_RET[1]['TYPE']=='select' || true)
	{
		$stu_RET = GetStuList($extra);
		foreach($stu_RET as $stu)
			$RET[$stu['LETTER_GRADE']]++;

		$chart['chart_data'][0][0] = '';
		$chart['chart_data'][1][0] = 'Series';

		//$chart['chart_data'][0][] = _('No Value');
		//$chart['chart_data'][1][] = $totals_RET['*BLANK*'][1]['COUNT'];			
		foreach($grades as $option)
		{
			$chart['chart_data'][0][] = $option;
			$chart['chart_data'][1][] = $RET[$option];
		}
	}
	
	if($_REQUEST['chart_type']!='list')
		SendChartData($chart);
}

if(!$_REQUEST['modfunc'])
{
	unset($_REQUEST['PHPSESSID']);
	echo '<FORM action=Modules.php?modname='.$_REQUEST['modname'].'&amp;chart_type='.str_replace(' ','+',$_REQUEST['chart_type']).' method=POST>';
	DrawHeader(ProgramTitle());
	
	//$advanced_link = " <A HREF=# onclick='remote = window.open(\"Modules.php?modname=$_REQUEST[modname]&modfunc=search&assignment_id=$_REQUEST[assignment_id]&chart_type=$_REQUEST[chart_type]&day_start=$_REQUEST[day_start]&day_end=$_REQUEST[day_end]&month_start=$_REQUEST[month_start]&month_end=$_REQUEST[month_end]&year_start=$_REQUEST[year_start]&year_end=$_REQUEST[year_end]&include_top=false\",\"\",\"scrollbars=yes,resizable=yes,width=700,height=600\"); remote.opener = window;'>"._('Advanced')."</A>";

	DrawHeader($assignment_select.$advanced_link,'<INPUT type=submit value='._('Go').'>');


	$width = 30*count($grades) < 500 ? 600 : 30*count($grades)+100;
	if($_REQUEST['chart_type']=='column')
		$height = 500;
	elseif($_REQUEST['chart_type']=='3d pie')
	{
		$height = $width-100;
		$width = 600;
	}
	
	echo '<BR>';
	if($_REQUEST['assignment_id'])
	{
		$tmp_REQUEST = $_REQUEST;
		unset($tmp_REQUEST['chart_type']);
		$link = PreparePHP_SELF($tmp_REQUEST);
		$tabs = array(array('title'=>_('Column'),'link'=>str_replace($_REQUEST['modname'],$_REQUEST['modname'].'&amp;chart_type=column',$link)),array('title'=>_('Pie'),'link'=>str_replace($_REQUEST['modname'],$_REQUEST['modname'].'&amp;chart_type=3d+pie',$link)),array('title'=>_('List'),'link'=>str_replace($_REQUEST['modname'],$_REQUEST['modname'].'&amp;chart_type=list',$link)));

		$_FOCUS['selected_tab'] = str_replace($_REQUEST['modname'],$_REQUEST['modname'].'&amp;chart_type='.str_replace(' ','+',$_REQUEST['chart_type']),$link);
		PopTable('header',$tabs,'',0);

		if($_REQUEST['chart_type']=='list')
		{
			$chart_data = array('0'=>'');

			// IGNORE THE 'Series' ELEMENT
			unset($chart['chart_data'][1][0]);
			foreach($chart['chart_data'][1] as $key=>$value)
				$chart_data[] = array('TITLE'=>$chart['chart_data'][0][$key],'VALUE'=>$value);
			unset($chart_data[0]);
			ListOutput($chart_data,array('TITLE'=>_('Option'),'VALUE'=>_('Number of Students')),_('Grade'),_('Grades'));
		}
		else
		{
			$_REQUEST['modfunc'] = 'SendChartData';
			$_REQUEST['_FOCUS_PDF'] = 'true';
			echo InsertChart("http://".$_SERVER['HTTP_HOST'].substr($_SERVER['SCRIPT_NAME'],0,strrpos($_SERVER['SCRIPT_NAME'],'/'))."/assets/SWF/charts.swf",str_replace('&amp;','&',PreparePHP_SELF()),$width,$height,'FFFFFF');
			unset($_REQUEST['_FOCUS_PDF']);
		}
		PopTable('footer');
	}
	echo '</FORM>';
}

function _makeNumeric($number,$column)
{	global $max_min_RET,$chart,$diff,$mins;
	
	if(!$number)
		$number=0;
	if($diff==0)
	{
		$chart['chart_data'][0][1] = $number;
		$chart['chart_data'][1][1]++;
	}
	elseif($diff<5)
	{
		$chart['chart_data'][0][((int) $number - (int) $max_min_RET[1]['MIN']+1)] = (int) $number;
		$chart['chart_data'][1][((int) $number - (int) $max_min_RET[1]['MIN']+1)]++;
	}
	else
	{
		for($i=1;$i<=5;$i++)
		{
			if(($number>=$mins[$i] && $number<$mins[$i+1]) || $i==5)
			{
				$chart['chart_data'][1][$i]++;
				break;
			}
		}
	}
	
	return;
}

function _makeGrade($value,$column)
{	global $THIS_RET,$total_points,$current_RET,$percent_RET,$programconfig;

	if(!is_numeric($_REQUEST['assignment_id']) && !$_REQUEST['student_id'])
	{
		if($programconfig['WEIGHT']=='Y' && count($percent_RET[$THIS_RET['STUDENT_ID']]))
		{
			$total = 0;
			foreach($percent_RET[$THIS_RET['STUDENT_ID']] as $type_id=>$type)
				$total += $type[1]['PARTIAL_PERCENT'];
		}
		elseif($current_RET[$THIS_RET['STUDENT_ID']][1]['TOTAL_POINTS'])
			$total = $current_RET[$THIS_RET['STUDENT_ID']][1]['POINTS'] / $current_RET[$THIS_RET['STUDENT_ID']][1]['TOTAL_POINTS'];
		else
			$total = 0;

		return _makeLetterGrade($total,UserCoursePeriod());
	}
	else
	{
		if($current_RET[$THIS_RET['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS']!='*')
			return _makeLetterGrade($current_RET[$THIS_RET['STUDENT_ID']][$_REQUEST['assignment_id']][1]['POINTS']/$total_points,UserCoursePeriod());
		else
			return _('N/A');
	}
}
?>